package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.vo.CellLocationRequest;
import com.ruoyi.system.domain.vo.CellLocationResponse;
import com.ruoyi.system.service.CellLocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@Service
public class CellLocationServiceImpl implements CellLocationService {

    @Autowired
    private RestTemplate restTemplate;

    // API地址
//    private static final String API_URL = "https://api.tanshuapi.com/api/cell/v1/index";
    private static final String API_URL = "http://api.cellocation.com:84/cell/";

    @Override
    public CellLocationResponse getCellLocation(CellLocationRequest request) {
        // 构建请求参数，这里以URL参数为例
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//        params.add("key", "8a51f1b11acf436e6f3668b814ca8a15");
        params.add("mcc", "460");
        params.add("mnc", "0");
//        params.add("lac", request.getLac());
//        params.add("cellid", request.getCid());
        params.add("lac", request.getLac());
        params.add("ci", request.getCid());
        params.add("output", "json");

        // 根据API文档添加其他必要参数，例如可能的密钥（key）或签名

        // 构建带参数的URL
        String url = API_URL + "?" + buildQueryString(params);

        // 发送GET请求[citation:2]
        ResponseEntity<CellLocationResponse> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                CellLocationResponse.class
        );

        return response.getBody();
    }

    /**
     * 构建查询字符串，处理URL编码
     */
    private String buildQueryString(MultiValueMap<String, String> params) {
            return params.entrySet().stream()
                    .flatMap(entry -> entry.getValue().stream()
                            .map(value -> {
                                try {
                                    return entry.getKey() + "=" + URLEncoder.encode(value, StandardCharsets.UTF_8.name());
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            }))
                    .collect(Collectors.joining("&"));

    }

    public static void main(String[] args) {
        System.out.println(StandardCharsets.UTF_8.name());
    }

}